# coding=utf-8
import arcpy
import math
import json

path = r'D:\WorkData\20250712四川河流\0813处理'
arcpy.env.workspace = path
arcpy.env.overwriteOutput = True
spatial_ref = arcpy.SpatialReference(4326)
riv = r'D:\WorkData\20250712四川河流\0813处理\rivs.shp'.decode('utf-8')
lp = r'D:\WorkData\20250712四川河流\0813处理\p_dis.shp'.decode('utf-8')

cs1 = arcpy.da.SearchCursor(lp,['SHAPE@','SHAPE@x','SHAPE@y','name','dis','n_riv_name','n_riv_id','n_riv_lv','FID','rivid'])
j=0
for row1 in cs1:
    try:
        print j, row1[3], row1[5], row1[6]
        n_riv_id = row1[6]
        expression = "rivId = '{}'".format(n_riv_id)
        cs2 = arcpy.da.SearchCursor(riv, ['SHAPE@WKT', 'SHAPE@', 'rivid'], where_clause=expression)
        WKT = [row[0] for row in cs2][0]
        cs2.reset()

        dis = 1
        insIndex = 0
        cs3 = arcpy.da.SearchCursor(riv, ['SHAPE@'], where_clause=expression, explode_to_points=True)
        i = 0
        for row3 in cs3:
            if row1[0].distanceTo(row3[0]) < dis:
                insIndex = i
                dis = row1[0].distanceTo(row3[0])
            i += 1
        cs3.reset()

        pointList = WKT.split('((')[1].split('))')[0].split(', ')

        x1 = float(pointList[insIndex].split(' ')[0])
        y1 = float(pointList[insIndex].split(' ')[1])
        x2 = float(pointList[insIndex - 1].split(' ')[0])
        y2 = float(pointList[insIndex - 1].split(' ')[1])

        segmentLength = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
        pointX = row1[1]
        pointY = row1[2]
        pToSegmentSP = math.sqrt((pointX - x2) ** 2 + (pointY - y2) ** 2)
        if (segmentLength > pToSegmentSP):
            pointList.insert(insIndex, ('%.15f %.15f'%(pointX, pointY)).decode('utf8'))
        else:
            pointList.insert(insIndex + 1, ('%.15f %.15f'%(pointX, pointY)).decode('utf8'))
        with arcpy.da.UpdateCursor(riv, 'SHAPE@WKT', where_clause=expression) as yb:
            for row in yb:
                N_WKT = 'MULTILINESTRING ((%s))' % ','.join(pointList)
                row[0] = N_WKT
                yb.updateRow(row)
        j += 1
    except Exception as e:
        print '!!!!!!!!!!!!!!!!{}!!!!!!!!!!!'.format(row1[6])

